import { downloadTemplateApi } from "@/api/common/";
import FormHook from "@/hook/formHook";
import { GeneraDataType } from "@/interface";
import { message } from "ant-design-vue";
import CommonHook from "@/hook/commonHook";
import type { UploadProps } from "ant-design-vue";

export default function OperationHook(state: GeneraDataType) {
  const { formState, formDataRef, emit, submitLoading, drawerOpts, downloadType, uploadRequest, templateName, maxCount } = state;
  const { downloadFileByUrl } = CommonHook();
  const { resetFields } = FormHook({ formState });
  const onFinish = () => {
    const formData = new FormData();
    // formData.append("file", formState.file[0]);

    if (maxCount.value !== 1) {
      formState.file.forEach((file: any) => {
        formData.append("file", file);
      });
    } else {
      formData.append("file", formState.file[formState.file.length - 1]);
    }

    submitLoading.value = true;
    return uploadRequest
      .value(formData)
      .then((res: any) => {
        const { code, data } = res;
        console.log(res);

        if (code === 200 && (!Array.isArray(data) || !data?.length || !data)) {
          message.success("操作成功");
          resetFields();
          formDataRef.value.clearValidate();
          emit("submit");
        } else {
          drawerOpts.title = `失败信息`;
          drawerOpts.width = "1200px";
          drawerOpts.component = "ErrorMessage";
          drawerOpts.passData = data;
          drawerOpts.visible = true;
        }

        formData.delete("file");
        formState.file = [];
      })
      .finally(() => {
        submitLoading.value = false;
      });
  };

  // 导入文件
  const uploadRequestHandle = (e: any) => {
    formState.file = [e.file];
    e.onProgress({ percent: 100 });
  };

  // 下载模板
  const downloadTemplateHandle = () => {
    return downloadTemplateApi({ type: downloadType.value }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        downloadFileByUrl(data, `${templateName[downloadType.value]}.xlsx`);
      }
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };

  const handleRemove: UploadProps["onRemove"] = file => {
    const index = formState.file.indexOf(file);
    const newFileList = formState.file.slice();
    newFileList.splice(index, 1);
    formState.file = newFileList;
  };
  const beforeUpload: UploadProps["beforeUpload"] = file => {
    formState.file = [...(formState.file || []), file];
    return false;
  };

  return {
    onFinishFailed,
    onFinish,
    resetHandle,
    resetFields,
    uploadRequestHandle,
    downloadTemplateHandle,
    handleRemove,
    beforeUpload
  };
}
